package com.example.demo.service;

import com.example.demo.model.MonkeyBean;
import com.example.demo.model.UserEntity;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.*;

/**
 * 代码生成 服务层处理
 */
@Service
public class GenService {
    private static final Logger log = LoggerFactory.getLogger(GenService.class);

    /**
     * 生成代码
     */
    public String generatorCode(String template, String outpath, String outfile) {
        log.debug("开始生成代码...");

        // 初始化vm环境
        initVelocity();

        // 获取模板信息，模板变量内容绑定
        VelocityContext context = getVelocityContext();

        // 渲染模板
        StringWriter sw = new StringWriter();
        Template tpl = Velocity.getTemplate(template, "UTF-8");
        tpl.merge(context, sw);
        String code = "" ;
        try {
            // 临时写入中间文件，方便调测
            code = writeTmpFile(tpl, outpath, outfile, context);
        } catch (IOException e) {
            log.error("渲染模板失败!", e);
        }
        return code;
    }


    /**
     * 生成文件
     *
     * @param tpl
     * @param filename
     * @param context
     * @throws IOException
     */
    private String writeTmpFile(Template tpl, String path, String filename, VelocityContext context) throws IOException {
        log.debug("生成代码文件");

        // 创建目录
        new File(path).mkdirs();

        // 创建输出文件
        File file = new File(path, filename);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        if (!file.exists()) {
            file.createNewFile();
        }

        // 模板生成到文件
        FileOutputStream outStream = new FileOutputStream(file);
        OutputStreamWriter writer = new OutputStreamWriter(outStream, "UTF-8");
        BufferedWriter sw = new BufferedWriter(writer);
        tpl.merge(context, sw);
        sw.flush();
        sw.close();
        outStream.close();
        log.trace("成功生成Java文件:" + path + filename);

        // 模板生成到字符串
        StringWriter stringWriter = new StringWriter();
        tpl.merge(context, stringWriter);
        String result = stringWriter.toString();

        return result;
    }

    /**
     * 获取模板信息
     *
     * @return 模板列表
     */
    public VelocityContext getVelocityContext() {
        log.debug("java对象数据传递到模板文件vm");
        VelocityContext velocityContext = new VelocityContext();

        // 模板变量绑定
        velocityContext.put("customer", buildDataMap());
        velocityContext.put("list", buildDataList());
        velocityContext.put("user", new UserEntity("zhang", "pwd" + new Random().nextInt(999)));
        velocityContext.put("monkey", new MonkeyBean());

        return velocityContext;
    }

    public Map buildDataMap() {
        Map<String, String> map = new HashMap<>();
        map.put("name", "demo111");
        return map;
    }

    public List buildDataList() {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add("item-" + new Random().nextInt(1000));
        }
        return list;
    }


    /**
     * 初始化vm
     */
    public void initVelocity() {
        log.debug("初始化vm");
        Properties p = new Properties();
        try {
            // 加载classpath目录下的vm文件
            p.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
            // 定义字符集
            p.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
            p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
            // 初始化Velocity引擎，指定配置Properties
            Velocity.init(p);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
